// Change theme plugin
// eslint-disable-next-line eslint-comments/abdeils - enable - pair;
/* eslint-disable import/no-extraneous-dependencies */
import ThemeColorReplacer from 'webpack-theme-color-replacer';
import generate from '@ant-design/colors/lib/generate';
import path from 'path';

function getModulePackageName(module: { context: string }) {
    if (!module.context) return null;

    const nodeModulesPath = path.join(__dirname, '../node_modules/');
    if (module.context.substring(0, nodeModulesPath.length) !== nodeModulesPath) {
        return null;
    }

    const moduleRelativePath = module.context.substring(nodeModulesPath.length);
    const [moduleDirName] = moduleRelativePath.split(path.sep);
    let packageName: string | null = moduleDirName;
    // handle tree shaking
    if (packageName && packageName.match('^_')) {
        // eslint-disable-next-line prefer-destructuring
        packageName = packageName.match(/^_(@?[^@]+)/)![1];
    }
    return packageName;
}

export default (config: any) => {
    if (process.env.NODE_ENV !== 'production') {
        config.plugin('webpack-theme-color-replacer').use(ThemeColorReplacer, [
            {
                fileName: 'css/theme-colors-[contenthash:8].css',
                matchColors: getAntdSerials('#1890ff'), // 主色系列
                // 改变样式选择器，解决样式覆盖问题
                changeSelector(selector: string): string {
                    switch (selector) {
                        case '.ant-calendar-today .ant-calendar-date':
                            return ':not(.ant-calendar-selected-date)' + selector;
                        case '.ant-btn:focus,.ant-btn:hover':
                            return '.ant-btn:focus:not(.ant-btn-primary),.ant-btn:hover:not(.ant-btn-primary)';
                        case '.ant-btn.active,.ant-btn:active':
                            return '.ant-btn.active:not(.ant-btn-primary),.ant-btn:active:not(.ant-btn-primary)';
                        default:
                            return selector;
                    }
                }
                // isJsUgly: true,
            }
        ]);
    }

    // optimize chunks
    config.optimization
        // share the same chunks across different modules
        .runtimeChunk(false)
        .splitChunks({
            chunks: 'async',
            name: 'vendors',
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                antd: {
                    name: 'antd', // split antd into a single package
                    test: /[\\/]node_modules[\\/]antd(.*)/ // in order to adapt to cnpm
                },
                vendors: {
                    test: (module: { context: string }) => {
                        const packageName = getModulePackageName(module) || '';
                        if (packageName) {
                            return [
                                'bizcharts',
                                'gg-editor',
                                'g6',
                                '@antv',
                                'gg-editor-core',
                                'bizcharts-plugin-slider'
                            ].includes(packageName);
                        }
                        return false;
                    },
                    name(module: { context: string }) {
                        const packageName = getModulePackageName(module);
                        if (packageName) {
                            if (['bizcharts', '@antv_data-set'].indexOf(packageName) >= 0) {
                                return 'viz'; // visualization package
                            }
                        }
                        return 'misc';
                    }
                }
            }
        });
};

const getAntdSerials = (color: string) => {
    const lightNum = 9;
    const devide10 = 10;
    // 淡化（即less的tint）
    const lightens = new Array(lightNum).fill(undefined).map((_, i: number) => {
        return ThemeColorReplacer.varyColor.lighten(color, i / devide10);
    });
    const colorPalettes = generate(color);
    const rgb = ThemeColorReplacer.varyColor.toNum3(color.replace('#', '')).join(',');
    return lightens.concat(colorPalettes).concat(rgb);
};
